package com.controller;

import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.model.Course;
import net.sf.json.JSONObject;

import java.util.List;

/**
 * Created by Hexun on 2017/5/28 0028.
 */
public class CourseController extends Controller {
    /**
    *@Author:HeXun
    *@Description:显示科目列表
    *@Date:2017/6/1 0001
    */
    public void showCourses() {
        List<Course> CourseList = Course.dao.find("select * from courses");
        setAttr("CourseList", CourseList);
        render("CoursesManage.jsp");
    }

    /**
    *@Author:HeXun
    *@Description:添加科目
    *@Date:2017/6/1 0001
    */

    public void addCourse() {
        String name = getPara("kemu");
        if (name != "null" && validateName(name)) {
            try {
                new Course().set("name", name).save();
                setAttr("result", "添加成功");
            } catch (Exception e) {
                setAttr("result", "添加失败,检查科目名是否重复");
            }
        } else {
            setAttr("result", "添加失败,检查格式是否正确");
        }
        renderJson();
    }
    /**
    *@Author:HeXun
    *@Description:更改科目名字
    *@Date:2017/6/1 0001
    */
    public void editCourse() {
        String name = getPara("operatorName");
        String id = getPara("operatorId");

        try {
            if (new Course().findById(id).set("name", name).update()) {
                setAttr("result", "success");
            } else {
                setAttr("result", "fail");
            }
        } catch (Exception e) {
            setAttr("result", "fail");
        }

        renderJson();
    }
    /**
    *@Author:HeXun
    *@Description:根据科目ID删除科目
    *@Date:2017/6/1 0001
    */
    public void deleteCourse() {
        int id = getParaToInt(0);
        String message = null;
        if (Course.dao.deleteById(id)) {
            setAttr("result", "success");
        } else {
            setAttr("result", "fail");
        }
        renderJson();
    }
    /*对科目名字的验证，不能为空且为XX-XX格式*/
    public boolean validateName(String name) {
        if (name.indexOf("-") != -1) {
            String[] courses = name.split("-");
            String nianji = courses[0];
            String course = courses[1];
            if (nianji == "" || nianji == null) {
                return false;
            } else if (course == "" || course == null) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}
